<template>
  <div>
    <el-dialog
      v-model="state.show"
      :title="hasAccount ? '编辑对账单' : '新增对账单'"
      width="520px"
      modal-class="unReconciled-dailog"
    >
      <el-form label-suffix="：" label-width="100px" size="small">
        <el-form-item label="对账单号">
          <el-input
            v-model="state.modfiyForm.doccode"
            placeholder="请输入"
            style="width: 100%"
            :disabled="true"
          ></el-input>
        </el-form-item>
        <el-form-item label="币种">
          <el-select
            v-model="state.modfiyForm.currencyCode"
            placeholder="请选择币种"
            style="width: 100%"
            clearable
            disabled
            filterable
            remote
            :remote-method="getCurrentData"
            :loading="currentLoading"
          >
            <el-option
              v-for="item in current"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
              <span style="float: left"> {{ item.label }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="结算对象名称" label-width="100px">
          <el-select
            v-model="state.modfiyForm.entId"
            placeholder="请选择结算对象"
            style="width: 100%"
            clearable
            filterable
            remote
            disabled
            :remote-method="getBusDetail"
            @change="changeEntName"
            :loading="state.settlementLoading"
          >
            <el-option
              v-for="item in state.settlementList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="state.modfiyForm.memo"
            placeholder="请输入"
            style="width: 100%"
          ></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <div>
          <el-button type="default" @click="state.show = false">取消</el-button>
          <el-button type="primary" @click="modifySubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, defineProps, defineEmits } from 'vue'
import request from '@/public/request'
import { ElMessage } from 'element-plus'

const props = defineProps({
  DocType: {
    type: Number,
    required: true
  },
  // 是否已对账
  hasAccount: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['getList'])

const state = reactive({
  show: false,
  // 发票修改信息
  modfiyForm: {
    doccode: '', //对账单号
    entId: '', //费用Id
    entFullname: '', //费用名称
    doctype: props.DocType, //1:应收 0：应付
    memo: '', //备注
    id: '',
    feeIds: [],
    DocStatus: 0,
    currencyCode: ''
  },
  settlementList: [],
  settlementLoading: false,
  currentLoading: false,
  current: []
})

// 获取币种类型
const getCurrentData = async (val) => {
  state.currentLoading = true
  let res = await this.$http.get('/api/base/currency/dropdownlist', {
    keywords: val
  })
  state.current = res.map((item) => {
    return {
      label: item.currencyCode + '|' + item.currencyName,
      value: item.currencyCode
    }
  })
  state.currentLoading = false
}

// 获取结算对象的数据
const getBusDetail = async (val) => {
  state.settlementLoading = true
  let res = await request.get('/api/buenterprise/dropdownlist', {
    KeyWords: val
  })
  res.forEach((item) => {
    item.label = item.entFullname
    item.value = item.id
  })
  state.settlementList = res
  state.settlementLoading = false
}

const resetModfiyForm = () => {
  state.modfiyForm = {
    doccode: '', //对账单号
    entId: '', //费用Id
    entFullname: '', //费用名称
    doctype: props.DocType, //1:应收 0：应付
    memo: '', //备注
    id: '',
    feeIds: [],
    currencyCode: ''
  }
}
// 打开弹窗
const openDialog = async (row) => {
  resetModfiyForm()
  let api = ''
  if (!props.hasAccount) {
    // add
    api = '/api/bucode/doccodeSerialByCode'
    const entId = [row[0].entId]
    const entFullname = [row[0].entFullname]
    const feeIds = []
    const currency = [row[0].currency]
    row.forEach((item) => {
      feeIds.push(item.id)
      if (!entId.some((val) => item.entId === val)) {
        entId.push(item.entId)
      }
      if (!currency.some((val) => item.currency === val)) {
        currency.push(item.currency)
      }
    })
    if (entId.length == 1) {
      state.modfiyForm.entId = entId[0]
      state.modfiyForm.entFullname = entFullname[0]
      state.settlementList = [
        {
          label: row[0].entCode,
          value: entId[0]
        }
      ]
      state.modfiyForm.currencyCode = currency[0]
    }
    state.modfiyForm.feeIds = feeIds
    let res = await request.get(api, {
      code: props.DocType == 1 ? 'SYS_BALANCE_I' : 'SYS_BALANCE_C'
    })
    state.modfiyForm.doccode = res ? res : ''
  } else {
    // edit
    if (row.entId) {
      let res = await request.get('/api/buenterprise/dropdownlist', {
        id: row.entId
      })
      res.forEach((item) => {
        item.label = item.entCode
        item.value = item.id
      })
      state.settlementList = res
      state.modfiyForm = {
        id: row.id,
        doccode: row.doccode, //对账单号
        entId: row.entId, //费用Id
        entFullname: row.entFullname, //费用名称
        doctype: props.DocType,
        memo: '', //备注
        currencyCode: row.currencyCode
      }
    }
  }
  state.show = true
}

const changeEntName = (val) => {
  if (val) {
    state.settlementList.forEach((item) => {
      if (item.id == val) {
        state.modfiyForm.entFullname = item.entName
      }
    })
  }
}

// 对账单提交
const modifySubmit = async () => {
  if (!state.modfiyForm.entId) {
    ElMessage.warning('结算对象不能为空!')
    return
  }
  let api = ''
  if (!props.hasAccount) {
    api = '/api/docbalance/createBalance'
    delete state.modfiyForm.id
  } else {
    api = '/api/docbalance/updateBalanceMemo'
    delete state.modfiyForm.feeIds
  }
  let res = await request.post(api, state.modfiyForm)
  if (res.status) {
    // ctx.emit('getList')
    emit('getList')
    ElMessage.success('成功')
    state.show = false
  } else {
    ElMessage.warning(res.message)
  }
}

defineExpose({
  openDialog
})
</script>

<style scoped></style>
<style lang="scss">
.unReconciled-dailog {
  .el-dialog__header {
    border-bottom: 1px solid #e8e8e8;
  }

  .el-dialog__footer {
    border-top: 1px solid #e8e8e8;

    div {
      display: flex;
      justify-content: flex-end;
      align-items: center;
    }
  }
}
</style>
